/*
   Copyright 2021 Hiroshi.tao

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package lib

import (
	"bytes"
	"errors"
	"text/template"

	"tcw.im/rtfd/pkg/util"

	"tcw.im/gtc"
)

// 渲染nginx配置文件所需参数，前四项是必填项，后面选填，最后Now、SSL、SSLCFG会自动填充
type nginxOptions struct {
	Name    string // 文档项目名
	Lang    string // 文档默认语言
	Domain  string // 默认域名或自定义域名
	DocsDir string // 文档项目所在的父目录

	Single bool   // 单一版本
	SSLCrt string // ssl公钥
	SSLKey string // ssl私钥

	Now    string // 当前时间
	SSL    bool   // 是否开启ssl
	SSLCFG string // ssl配置内容
}

func (opt *nginxOptions) render() (conf string, err error) {
	if opt.Name == "" || opt.Lang == "" || opt.Domain == "" || opt.DocsDir == "" {
		err = errors.New("found empty field")
		return
	}
	if opt.Now == "" {
		opt.Now = util.GetNow()
	}
	if gtc.IsFile(opt.SSLCrt) && gtc.IsFile(opt.SSLKey) {
		ssltpl, e := template.New("ssl").Parse(nginxSSLTPL())
		if e != nil {
			err = e
			return
		}
		var sslcfg bytes.Buffer
		e = ssltpl.Execute(&sslcfg, struct{ SSLCrt, SSLKey string }{opt.SSLCrt, opt.SSLKey})
		if e != nil {
			err = e
			return
		}
		opt.SSL = true
		opt.SSLCFG = sslcfg.String()
	} else {
		opt.SSL = false
	}

	var tpl string
	if opt.Single {
		tpl = nginxSingleTPL()
	} else {
		tpl = nginxMultiTPL()
	}
	tmpl, err := template.New("nginx").Parse(tpl)
	if err != nil {
		return
	}

	var result bytes.Buffer
	err = tmpl.Execute(&result, opt)
	if err != nil {
		return
	}
	return result.String(), nil
}

func nginxMultiTPL() string {
	// 通用模板，需要参数：
	return `#: Automatic generated by rtfd at {{ .Now }}
server {
    listen 80;
    {{- if .SSL }}
    listen 443 ssl http2;
    {{- end }}
    server_name {{ .Domain }};
    charset utf-8;
    root {{ .DocsDir }}/{{ .Name }}/;
    index index.html master.html;
    set $home /{{ .Lang }}/latest;
    error_page 403 =404 /404.html;
    {{- if .SSL -}}
        {{ .SSLCFG }}
    {{- end }}
    location / {
        if (-e $document_root$home$document_uri) {
            return 302 $home$document_uri$is_args$args;
        }
    }
}
`
}

func nginxSingleTPL() string {
	// 单一版本的模板，参数要求同通用模板
	return `#: Automatic generated by rtfd at {{ .Now }}
server {
    listen 80;
    {{- if .SSL }}
    listen 443 ssl http2;
    {{- end }}
    server_name {{ .Domain }};
    charset utf-8;
    root {{ .DocsDir }}/{{ .Name }}/{{ .Lang }}/latest/;
    index index.html master.html;
    {{- if .SSL -}}
        {{ .SSLCFG }}
    {{- end }}
}
`
}

func nginxSSLTPL() string {
	// SSL模板，需要传递证书、私钥三个参数
	return `
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
    ssl_certificate {{ .SSLCrt }};
    ssl_certificate_key {{ .SSLKey }};
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 114.114.114.114 valid=300s;
    resolver_timeout 5s;
    ssl_session_tickets on;
    ssl_session_timeout  10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;
    ssl_prefer_server_ciphers on;
    add_header Strict-Transport-Security "max-age=31536000;preload";`
}
